package com.moive.news.tqnewsapplication.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.adapter.SearchAdapter;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.entity.SearchInfo;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.ui.fragment.FenLeiFragment;
import com.moive.news.tqnewsapplication.utils.GetSystemTimeUitl;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.mylistview.SecondXListView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/12/26.
 */

public class SearchActivity extends BaseActivity implements SecondXListView.IXListViewListener {
    @BindView(R.id.search_back)
    ImageView searchBack;
    @BindView(R.id.person_filter_edit)
    EditText personFilterEdit;
    @BindView(R.id.ivDeleteText)
    ImageView ivDeleteText;
    @BindView(R.id.search_btn_back)
    TextView searchBtnBack;
    @BindView(R.id.pub_all_listview)
    SecondXListView pubAllListview;
    String title = "";
    private Gson gson = new Gson();
    private int page = 1;
    SearchAdapter ad;
    List<SearchInfo.DataBean> list = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        ad = new SearchAdapter(SearchActivity.this);
        pubAllListview.setAdapter(ad);
        pubAllListview.setXListViewListener(this);
        pubAllListview.setPullLoadEnable(true);
        pubAllListview.setPullRefreshEnable(false);
        Intent intent = getIntent();
        if (intent != null) {
            title = intent.getStringExtra("title");
            if (!TextUtils.isEmpty(title)) {
                personFilterEdit.setText(title);
                search(title);
            }
        }
    }

    @OnClick({R.id.search_back, R.id.ivDeleteText, R.id.search_btn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_back:
                finish();
                break;
            case R.id.ivDeleteText:
                personFilterEdit.setText("");
                break;
            case R.id.search_btn_back:
                String s = personFilterEdit.getText().toString().trim();
                if (TextUtils.isEmpty(s)) {
                    ToastUtils.ShortToast("请输入你要关注好友的昵称");
                } else {
                    list.clear();
                    search(s);
                }
                break;
        }
    }
    private void search(String s) {
        OkHttpUtils.post()
                .addParams("token",PreferenceUtil.getString("token",""))
                .url(BaseApi.SEARCH)
                .addParams("nickName", s)
                .addParams("page", page + "")
                .addParams("rows", "10")
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        LogUtil.i(TAG,"SIZE="+jsonArray.length());
                        if (jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
                                SearchInfo.DataBean dataBean = gson.fromJson(jsonObject1 + "", SearchInfo.DataBean.class);
                                 list.add(dataBean);
                            }
                            ad.addItems(list);
                        }
                        if (jsonArray.length()==0){
                            ToastUtils.ShortToast("没有更多数据了！");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        page = 1;
        list.clear();

        ad.notifyDataSetChanged();
        stopOnLoad();
    }

    private void stopOnLoad() {
        pubAllListview.stopRefresh();
        pubAllListview.stopLoadMore();
        pubAllListview.setRefreshTime(GetSystemTimeUitl.getTime());
    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                search(personFilterEdit.getText().toString().trim());
                ad.notifyDataSetChanged();
                stopOnLoad();
            }
        }, 1000);
    }
}
